<template>
  <div class="form-container">
    <el-form
        :model="formData"
        ref="formRef"
        label-width="100px"
        :rules="formRules"
    >
      <!-- 头像上传 -->
      <el-form-item
          label="封面"
          prop="videoCover"
          style="justify-content: center; display: flex; align-items: center;"
      >
        <Upload
            :src="formData.videoCover"
            :handleAvatarChange="handleAvatarChange"
            :previewImage="previewImage"
        />
        <span style="margin-left: 4%; margin-right: 10px;">横图</span>
        <Upload
            :src="formData.videoChartCover"
            :handleAvatarChange="handleAvatarChanges"
            :previewImage="previewImages"
        />
      </el-form-item>

      <!-- 基础信息 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="作品标题" prop="title">
            <el-input v-model="formData.title" />
          </el-form-item>

          <el-form-item label="发布商" prop="title">
            <el-input v-model="formData.publisher" />
          </el-form-item>

          <el-form-item label="发布日期" prop="releaseDate">
            <el-date-picker
                v-model="formData.releaseDate"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%;"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="评分" prop="rating">
            <el-rate v-model="formData.rating" allow-half size="large"/>
          </el-form-item>

          <el-form-item label="总集数" prop="episode">
            <el-input-number
                v-model="formData.episode"
                :min="0"
                :controls="false"
                style="width: 100%;"
            />
          </el-form-item>

          <el-form-item label="地区" prop="region">
            <el-select
                v-model="formData.region"
                style="width: 100%;"
            >
              <el-option
                  v-for="item in regions"
                  :key="item"
                  :label="item"
                  :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 动态角色列表 -->
      <el-form-item label="主要角色" prop="mainCharacters">
        <div
            v-for="(char, index) in formData.mainCharacters"
            :key="index"
            class="character-item"
        >
          <el-input
              v-model="char.name"
              placeholder="角色名"
              style="width: 200px;"
          />
          <el-input
              v-model="char.cv"
              placeholder="声优"
              style="width: 200px; margin: 0 10px;"
          />
          <el-button
              type="danger"
              circle
              @click="removeCharacter(index)"
              :disabled="formData.mainCharacters.length === 1"
          >
            <el-icon><Remove /></el-icon>
          </el-button>
        </div>
        <el-button
            style="margin-left: 10px; "
            type="primary"
            @click="addCharacter"
        >
          添加角色
        </el-button>
      </el-form-item>

      <!-- 制作团队 -->
      <el-form-item label="制作团队">
        <el-form-item label="原作" prop="staff.originalAuthor">
          <el-input v-model="formData.staff.originalAuthor" placeholder="原作"/>
        </el-form-item>
        <el-form-item label="监督" prop="staff.director">
          <el-input v-model="formData.staff.director" placeholder="监督" />
        </el-form-item>
        <el-form-item label="系列构成" prop="staff.seriesComposer">
          <el-input v-model="formData.staff.seriesComposer" placeholder="系列构成"/>
        </el-form-item>
        <el-form-item label="角色设计" prop="staff.characterDesigner">
          <el-input v-model="formData.staff.characterDesigner" placeholder="角色设计"/>
        </el-form-item>
        <el-form-item label="音乐" prop="staff.music">
          <el-input v-model="formData.staff.music" placeholder="音乐"/>
        </el-form-item>
      </el-form-item>

      <!-- 标签输入 -->
      <el-form-item label="分类标签" prop="tags">
        <div class="tag-container">
          <el-tag
              v-for="(tag, index) in formData.tags"
              :key="index"
              closable
              @close="removeTag(index)"
          >
            {{ tag }}
          </el-tag>
          <el-input
              v-model="newTag"
              placeholder="输入标签后回车"
              @keyup.enter="addTag"
              class="tag-input"
          />
        </div>
      </el-form-item>

      <!-- 简介 -->
      <el-form-item label="作品简介" prop="introduction">
        <el-input
            v-model="formData.introduction"
            type="textarea"
            :rows="4"
            :maxlength="500"
            show-word-limit
        />
      </el-form-item>

      <!-- 状态 -->
      <el-form-item label="作品状态">
        <el-select
            v-model="formData.status"
            style="width: 200px;"
        >
          <el-option :value="0" label="待发布" />
          <el-option :value="1" label="更新中" />
          <el-option :value="2" label="已完结" />
        </el-select>
      </el-form-item>

      <!-- 状态 -->
      <el-form-item label="审核状态">
        <el-select
            v-model="formData.reviewStatus"
            style="width: 200px;"
        >
          <el-option :value="0" label="待审核" />
          <el-option :value="1" label="通过" />
          <el-option :value="2" label="驳回" />
        </el-select>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item style="float: right">
        <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitting"
        >
          提交
        </el-button>
        <el-button @click="handleReset">
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, watchEffect } from 'vue'
import { ElMessage, ElMessageBox,ElNotification } from 'element-plus'
import Upload from '@/components/Upload.vue'
import {PostFileImg} from "@/api/file.js";
import {addVideoInfo, updateVideoInfo} from "@/api/video.js";

const props = defineProps({
  initialData: {
    type: Object
  }
})

const emit = defineEmits(['submit']);

// 表单数据
const formData = reactive({ ...props.initialData })
const formRef = ref(null)
const newTag = ref('')
const submitting = ref(false)
const regions = ['中国', '日本', '美国', '韩国']

// 表单验证规则
const formRules = reactive({
  title: [{ required: true, message: '请输入作品标题', trigger: 'blur' }],
  releaseDate: [
    { required: true, message: '请选择发布日期', trigger: 'change' }
  ]
})

// 预览图片
const previewImage = ref('');

// 处理头像选择变化
const handleAvatarChange = async (file) => {
  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('请上传图片文件!');
    return false;
  }

  // 验证文件大小
  const isLt2M = file.raw.size / 1024 / 1024 < 4;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 4MB!');
    return false;
  }

  const response = await PostFileImg(file.raw);
  if(response.data.code !== 200){
    ElMessage.error(response.data.message);
    return;
  }
  formData.videoCover = response.data.data;

  // 创建预览图
  const reader = new FileReader();
  reader.onload = (e) => {
    previewImage.value = e.target.result;
  };
  reader.readAsDataURL(file.raw);

  return false; // 阻止自动上传
};

// 预览图片
const previewImages = ref('');

// 处理头像选择变化
const handleAvatarChanges = async (file) => {
  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('请上传图片文件!');
    return false;
  }

  // 验证文件大小
  const isLt2M = file.raw.size / 1024 / 1024 < 4;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 4MB!');
    return false;
  }

  const response = await PostFileImg(file.raw);
  if(response.data.code !== 200){
    ElMessage.error(response.data.message);
    return;
  }
  formData.videoChartCover = response.data.data;

  // 创建预览图
  const reader = new FileReader();
  reader.onload = (e) => {
    previewImages.value = e.target.result;
  };
  reader.readAsDataURL(file.raw);

  return false; // 阻止自动上传
};

// 角色操作
const addCharacter = () => {
  formData.mainCharacters.push({ name: '', cv: '' })
}

const removeCharacter = (index) => {
  if (formData.mainCharacters.length <= 1) return
  formData.mainCharacters.splice(index, 1)
}

// 标签操作
const addTag = () => {
  if (newTag.value.trim()) {
    formData.tags.push(newTag.value.trim())
    newTag.value = ''
  }
}

const removeTag = (index) => {
  formData.tags.splice(index, 1)
}

// 表单提交
const handleSubmit = async () => {
    if(formData.title === '' || formData.releaseDate === ''||formData.publisher===''){
      ElNotification.error('请填写完整信息');
      return;
    }
    const payload = {
      ...formData,
      mainCharacters: formData.mainCharacters.filter(c => c.name && c.cv),
      tags: formData.tags.filter(t => t.trim()),
      episode: Number(formData.episode),
      rating: Number(formData.rating) * 2,
    }
    if(props.initialData.videoId === '' || props.initialData.videoId === undefined){
      //新增
      await addVideoInfo(payload)
    }else{
      //编辑
      await updateVideoInfo(payload)
    }
    emit('submit', payload);
  submitting.value = false
}

// 表单重置
const handleReset = () => {
  ElMessageBox.confirm('确定要重置所有内容吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    Object.assign(formData, props.initialData)
    formRef.value.resetFields()
  })
}

// 监听初始数据变化
watchEffect(() => {
  Object.assign(formData, props.initialData)
})
</script>

<style scoped>
.form-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.character-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-input {
  width: 200px;
}

.mt-10 {
  margin-top: 10px;
}
:deep(.el-upload){
  width: 110px;
  height: 178px;
}
</style>
